package com.touchealth.test.touchealth;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.FileUrlResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.PrivateKey;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

/**
 * @author zhangyanqiang
 * @date 2020/9/21
 **/
@Slf4j
@Component
public class GuangDaImageUploadUtilTmp {

    private static String imagePath = "/data/accouting/image/";
    private static String targetUrl="https://nephele-st.sunlife-everbright.com:9800/securityupload/file";
    private static String  sourceUrl ="https://files-dev.touchealth.com/FsFF1JzwWtgQtNyYBxcmCTSChxnW.jpg";
    private static String appId="guangshubao";
    private static String policyNo ="123424789";
    private static String fileStorageId = "fileStorageId";
    private static String privateKey ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJhHwsOmfuLbWH47fMXDGbaF5oAwPoeMlC9yJr/5dJBNXPPtPkA//0n7JfY7XX/qNHlp98BQIkxUzIZBRLIsrg8gdb+K1InBL5/3p/5vsuGRBAgCxFvswXCfl5043RaEnvaxCrk6H3jdbwx3L2UpxrxXrpPZQ0Bgo6X61e8Bu2RPAgMBAAECgYA9Yl/+YjUv2V+Ysv4e8gCBdQRvlAMAvQhW/9ri8/mq2aSop2+6kpGkDttEoLWWBKDWeILoQOUyg9RWIiVA9YXL6+d+w/O3YnC0+oLM4tW9neHJvMn/L7MMHmwxQb+Bcz9Il9pavjB4r+1Il+lxy9egE5V5kNrJ1G29c/P3NvQKYQJBAPfZf5sOhGFexL73XWbjdsAEoZi1UbVhn/aYwlBv43rY3S6zAfniOrK3BkuMyEKhVP/8qZx2fYshx8KFEtdSz5cCQQCdSbhauyejTHPuBKZ74wupIyRNEVixGjOGvyxTsQUyCjR+2E0Y8Vbkj5dDKbz3LfiDCN17VogyDe8Gqwb4AagJAkEApb4K+XQBzuODCnl9OnrORKZUMjy+wV7hjBSnjQblxpcTglEu9x30RuLiEM+6c+RTZURfYERUvCAA5/H5oYi9TQJAeccbEjx3KwrFc1JsZ9zZKWII+BZnGe/UVw5qzn1vLVgTXuYvgxFQGnRGQ/zrzmDsWN+jQ5wypLZ/CyWdpqT5qQJAbfsqqA+w8Gtb7enp4kJ72BLcdtS+EYV+u/5+8oebj8uG4vYwhaHIYYfccRL8XDmTYmhMIqzVEbOloBoMrfiNow==";

    public static String uploadFile(String targetUrl,String sourceUrl, String appId,String policyNo,String privateKey, RestTemplate restTemplate){

        FileInputStream inputStream = null;
        try {
              if (!StringUtils.isEmpty(sourceUrl)){
                  String filePath = saveImageFromUrl(sourceUrl);
                  if (StringUtils.isEmpty(filePath)){
                      return null;
                  }
                  FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
                  inputStream = new FileInputStream(fileSystemResource.getFile());
                  String base64String = inputStreamToBase64String(inputStream);
                log.info("光大图片上传 file base64String is :{}",base64String);

                MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
                param.add("appId", appId);
                param.add("policyNo", policyNo);
                param.add("storageType", "test");
                param.add("file", fileSystemResource);
                param.add("saveDB", "Y");
                String startDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                param.add("startDateTime", startDateTime);
                //使用私钥获取签名
                String signStr = appId + "|" + policyNo + "|" + "Y" +"|"+startDateTime
                        + "|"+"test" +"|"+base64String.replaceAll("\\r", "").replaceAll("\\n", "");
                log.info("光大图片上传签名前:{}",signStr);
                PrivateKey privateKey1 = SignatureUtil.getPrivateKey(privateKey);
                String sign = SignatureUtil.sign(signStr, privateKey1);
                HttpHeaders headers = new HttpHeaders();
                headers.add("Authorization","Bearer " +
                        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cGxvYWRmaWxlIiwicm9sZSI6Imludm9rZSIsImlzcyI6Imd1YW5nc2h1YmFvIiwiZXhwIjoxOTAzMjQ0MTkzfQ.Zon4XTdtfLsAKKR_AaqnuMy8C8s3zuWoZcM_PZv3Bqw");
                headers.add("Signature",sign);
                HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<> (param, headers);
                String result =  restTemplate.postForObject(targetUrl, files, String.class);
                log.info("光大图片上传结果:{}",result);
                JSONObject json = JSONUtil.parseObj(result);
                String storageId = json.getStr(fileStorageId);
                storageId = storageId.substring(storageId.indexOf("{") +1,storageId.lastIndexOf("}"));
                log.info("返回图片存储Id:{}", storageId);
                return storageId;
            }else {
                log.info("传入的文件地址为空");
            }

        }catch (Exception e){
            log.error("上传图片失败:{}",e);
        }finally {
            try {
                if (inputStream != null){
                    inputStream.close();
                }
            }catch (Exception e){
                log.error("关闭异常:{}",e);
            }
        }
        return null;
    }

    public static String inputStreamToBase64String(InputStream inputStream) {
        byte[] data = null;
        try {
            data = new byte[inputStream.available()];
            int i = inputStream.read(data);
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(data);
        } catch (IOException e) {
            log.error("解析数据失败 :{}",e);
            return null;
        }
    }

    public static void main(String[] args) {

        RestTemplate restTemplate = new RestTemplate();
       uploadFile(targetUrl,sourceUrl,appId,policyNo,privateKey,restTemplate);

    }

    private static String saveImageFromUrl(String imageUrl){

        FileOutputStream fileOutputStream = null;
        HttpURLConnection httpURLConnection = null;
        BufferedInputStream in = null;
        try{

            URL url = new URL(sourceUrl);
            httpURLConnection = (HttpURLConnection)url.openConnection();
            in = new BufferedInputStream(httpURLConnection.getInputStream());
            FileUrlResource urlResource = new FileUrlResource(url);
            fileOutputStream = new FileOutputStream(imagePath+urlResource.getFilename());
            int length = 0;
            while((length = in.read()) != -1){
                fileOutputStream.write(length);
            }

            return imagePath+urlResource.getFilename();
        }catch (Exception e){

            log.info("保存图片异常:{}",e);
        }finally {
            try{
                if (fileOutputStream != null ){
                    fileOutputStream.close();
                }
                if (in != null){
                    in.close();
                }
                if (httpURLConnection != null){
                    httpURLConnection.disconnect();
                }
            }catch (Exception e){
                log.error("关闭异常");
            }


        }
        return null;

    }

}
